<template>
  <div class="myAddress">
    <div class="title">
      <span>我的收货地址</span>
      <el-button @click="(dialogVisible = true), (isAdd = true)">
        添加地址
      </el-button>
    </div>
    <div class="manage">
      <el-card v-for="item in address" :key="item.addressId" shadow="never">
        <div class="address">
          <div class="info">
            <div class="userInfo">
              {{ item.receiver }} , {{ item.phone }}
              <div class="default" v-if="item.isDefault == 1">默认地址</div>
            </div>
            <div class="addressInfo">{{ item.address }}</div>
          </div>
          <div class="controls">
            <el-button
              v-if="item.isDefault != 1"
              @click="setDefault(item.addressId)"
            >
              设为默认
            </el-button>
            <el-button
              type="primary"
              @click="
                (dialogVisible = true),
                  (isEdit = true),
                  Object.assign(addressBook, item)
              "
            >
              更改
            </el-button>
            <el-button type="danger" @click="deleteAddress(item.addressId)">
              删除
            </el-button>
          </div>
        </div>
      </el-card>
    </div>
  </div>

  <el-dialog
    v-model="dialogVisible"
    title="新增"
    width="600"
    :before-close="handleClose"
  >
    <el-form label-width="auto" style="max-width: 400px" :model="addressBook">
      <el-form-item label="收件人" :error="receiverError">
        <el-input v-model="addressBook.receiver" @blur="detectionReceiver()" />
      </el-form-item>
      <el-form-item label="手机号" :error="phoneError">
        <el-input v-model="addressBook.phone" @blur="detectionPhone()" />
      </el-form-item>
      <el-form-item label="详细地址" :error="addressError">
        <el-input v-model="addressBook.address" @blur="detectionAddress()" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose()">取消</el-button>
      <el-button type="primary" @click="addAddress()" v-if="isAdd">
        添加
      </el-button>
      <el-button type="primary" @click="editAddress()" v-if="isEdit">
        更改
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import {
  getUserAddressById,
  addUserAddress,
  editUserAddress,
  deleteUserAddress,
  setDefaultAddress
} from '@/apis/address'
import { onMounted, reactive, ref } from 'vue'
import { useUserStore } from '@/stores/index.js'
import { ElMessage } from 'element-plus'

const store = useUserStore()
const address = ref([])
const dialogVisible = ref(false)
const addressBook = reactive({})
const phoneError = ref('')
const receiverError = ref('')
const addressError = ref('')
const isAdd = ref(false)
const isEdit = ref(false)

onMounted(async () => {
  address.value = await getUserAddressById({
    userId: store.userInfo.data.userId
  }).then((res) => {
    return res.rows
  })
  console.log(address.value)
})

const handleClose = () => {
  phoneError.value = ''
  receiverError.value = ''
  addressError.value = ''
  console.log(addressBook)
  Object.assign(addressBook, {
    addressId: null,
    userId: null,
    receiver: '',
    phone: '',
    address: ''
  })
  dialogVisible.value = false
  isAdd.value = false
  isEdit.value = false
}

const detectionPhone = () => {
  if (
    addressBook.phone == null ||
    addressBook.phone == undefined ||
    addressBook.phone == ''
  ) {
    phoneError.value = '手机号不能为空'
    return false
  }
  const phoneRegex = /^1[3-9]\d{9}$/
  console.log(!phoneRegex.test(addressBook.phone))
  if (!phoneRegex.test(addressBook.phone)) {
    phoneError.value = '手机号格式错误，请输入正确的手机号'
    return false
  }
  phoneError.value = ''
  return true
}

const detectionReceiver = () => {
  if (
    addressBook.receiver == null ||
    addressBook.receiver == undefined ||
    addressBook.receiver == ''
  ) {
    receiverError.value = '收件人不能为空'
    return false
  }
  receiverError.value = ''
  return true
}
const detectionAddress = () => {
  if (
    addressBook.address == null ||
    addressBook.address == undefined ||
    addressBook.address == ''
  ) {
    addressError.value = '地址不能为空'
    return false
  }
  addressError.value = ''
  return true
}

const detection = () => {
  if (detectionAddress() & detectionReceiver() & detectionPhone()) {
    return true
  }
  return false
}

const addAddress = async () => {
  if (detection()) {
    console.log(addressBook)
    const add = {
      address: addressBook.address,
      receiver: addressBook.receiver,
      phone: addressBook.phone
    }
    console.log(JSON.stringify(add))
    let log = await addUserAddress(JSON.stringify(add))
    console.log(log)
    if (log.code == 200) {
      handleClose()
      address.value = await getUserAddressById({
        userId: store.userInfo.data.userId
      }).then((res) => {
        return res.rows
      })
      ElMessage.success('添加成功')
    } else {
      ElMessage.error('添加失败')
    }
  }
}

const editAddress = async () => {
  if (detection()) {
    let log = await editUserAddress(addressBook)
    console.log(log)
    if (log.code == 200) {
      handleClose()
      address.value = await getUserAddressById({
        userId: store.userInfo.data.userId
      }).then((res) => {
        return res.rows
      })
      ElMessage.success('修改成功')
    } else {
      ElMessage.error('修改失败')
    }
  }
}

const deleteAddress = async (addressId) => {
  let log = await deleteUserAddress(addressId)
  if (log.code == 200) {
    address.value = await getUserAddressById({
      userId: store.userInfo.data.userId
    }).then((res) => {
      return res.rows
    })
    ElMessage.success('删除成功')
  } else {
    ElMessage.error('删除失败')
  }
}

const setDefault = async (addressId) => {
  let log = await setDefaultAddress(addressId)
  if (log.code == 200) {
    address.value = await getUserAddressById({
      userId: store.userInfo.data.userId
    }).then((res) => {
      return res.rows
    })
    ElMessage.success('设置成功')
  } else {
    ElMessage.error('设置失败')
  }
}
</script>

<style scoped lang="scss">
.myAddress {
  height: 600px;
  padding: 10px 20px;
  overflow: hidden;
  .title {
    width: 100%;
    display: flex;
    justify-content: space-between;
    padding: 10px 20px;
    span {
      font-size: 20px;
    }
    border-bottom: 1px solid rgb(199.5, 201, 204);
  }
  .manage::-webkit-scrollbar {
    display: none;
  }
  .manage {
    height: 528px;
    overflow: scroll;
    .el-card {
      margin-bottom: 10px;
      margin-top: 10px;
    }
    .address {
      width: 100%;
      display: flex;
      justify-content: space-between;
      .info {
        display: flex;
        flex-direction: column;
        .addressInfo {
          font-size: 20px;
        }
        .userInfo {
          display: flex;
        }
        .default {
          margin-left: 20px;
          background-color: rgb(245, 74, 74);
          color: #fff;
          padding: 0 5px;
        }
      }
      .controls {
        padding: 5px;
      }
    }
  }
}
</style>
